package com.itbaizhan.common;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**基于Druid连接池获取数据库连接工具*/
//在工具类的方法都是静态方法
public class JdbcDruidUtil {
        //数据库连接池对象
    private static DataSource dataSource;
    static {
        try {
            //获取配置文件的字节输入流对象
            InputStream is = JdbcDruidUtil.class.getClassLoader().getResourceAsStream("druid.properties");
            //创建properties
            Properties properties = new Properties();
            //加载配置文件  这里的异常要try-catch
            properties.load(is);
            //创建连接池对象
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    //获取数据库连接对象
    public static Connection getConnection(){
        Connection connection = null;
        try{
            connection = dataSource.getConnection();
        }catch (Exception e){
            e.printStackTrace();
        }
        return connection;
    }

    /*关闭Connection对象*/
    public static void closeConnection(Connection connection){
        try {
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    /*提交事务*/
    public static void commit(Connection connection){
        try {
            connection.commit();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    /*事务回滚*/
    public static void rollback(Connection connection){
        try {
            connection.rollback();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    //关闭statement对象
    //因为PreparedStatement接口是Statement的子接口，所以不用再写多一
    //个方法关闭PreparedStatement
    public static void closeStatement(Statement statement){
        try {
            statement.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    //关闭ResultSet
    public static void closeResultSet(ResultSet resultSet){
        try {
            resultSet.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    //DML操作时关闭资源
    public static void closeResource(Statement statement,Connection connection){
        //先关闭Statement对象，再关闭Connection
        closeStatement(statement);
        closeConnection(connection);
    }
    //查询时关闭资源,方法可以重载，所以可以同名
    public static void closeResource(ResultSet resultSet,Statement statement,Connection connection){
        //后用先关
        //先关闭ResultSet
        closeResultSet(resultSet);
        //在闭Statement对象
        closeStatement(statement);
        //最后关闭Connection对象
        closeConnection(connection);
    }
}
